package com.lagou.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Roger
 * @date 2020/8/12 21:45
 * @description
 */
public class BeanFactory {

    private static Map<String, Object> ioc = new HashMap<String, Object>();

    static {
        try {
            InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");

            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            String xPath = "//bean";
            List<Element> list = document.selectNodes(xPath);
            for (Element element : list) {
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Object o = Class.forName(className).newInstance();
                ioc.put(id, o);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String beanId) {
        return ioc.get(beanId);
    }
}
